<?php
/**
 * CompleXml_Driver_File class
 *
 * @author Andrey Kucherenko (kucherenko.andrey@gmail.com)
 */
class CompleXml_Cache_Driver_File implements CompleXml_Cache_Driver_Interface{
    
    private $_options = array();

    private $_values = array();

    public function __construct($options = array())
    {
        $this->_options = $options;
    }

    public function set($id, $data, $lifeTime = false)
    {
        $this->_synchronyze();
        $this->_values[$id] = $data;
        $this->_save();
    }

    public function get($id)
    {
        $this->_synchronyze();
        return @$this->_values[$id];
    }

    public function delete($id)
    {
        $this->_synchronyze();
        unset($this->_values[$id]);
        $this->_save();
    }

    public function contains($id){
        $this->_synchronyze();
        return isset($this->_values[$id]);
    }

    public function flush()
    {
        unlink($this->_options['filename']);
    }

    private function _read()
    {
        $data = @file_get_contents($this->_options['filename']);
        $result = unserialize($data);
        if ($result!==false){
            $this->_values = $result;
        }else{
            $this->_values = array();
        }
    }

    private function _synchronyze()
    {
        if ((isset ($this->_options['synchronyze'])&&$this->_options['synchronyze'])||(empty($this->_values))){
            $this->_read();
        }
    }

    private function _save()
    {
        file_put_contents($this->_options['filename'], serialize($this->_values));
    }
}

